/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2023/8/24 14:48
@File     : create.go
@Project  : web_scaff
@Desc     :
*/
package user

import (
	"web_scaff/models"
	"web_scaff/models/response"
	sysValidator "web_scaff/pkg/validator"
	"web_scaff/service/user"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
)

type createRequest struct {
	Name     string `json:"name" binding:"required,max=10,min=6"`
	Phone    string `json:"phone" binding:"required"`
	Avatar   string `json:"avatar"`
	Username string `json:"username"`
	Pwd      string `json:"pwd"`
	RePwd    string `json:"re_pwd"`
}

func Create(c *gin.Context) {
	var req = new(createRequest)

	if err := c.ShouldBindJSON(req); err != nil {
		// 请求参数有误，直接返回响应
		zap.L().Error("添加用户失败", zap.Error(err))
		// 判断err是不是validator.ValidationErrors 类型
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			response.FailWithMsg("添加用户失败", c)
			return
		}
		response.FailWithMsg(sysValidator.RemoveTopStruct(errs.Translate(sysValidator.Trans)), c)
		return
	}

	u := &models.User{
		Name:     req.Name,
		Phone:    req.Phone,
		Avatar:   req.Avatar,
		Username: req.Username,
		Pwd:      req.Pwd,
	}

	if err := user.Create(u); err != nil {
		response.FailWithMsg(err.Error(), c)
		return
	}
	response.Success(c)
}
